package com.woniuxy.interceptor;

import com.alibaba.fastjson.JSON;
import com.woniuxy.util.JWTUtil;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.ResponseEnum;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author dingpf
 * @version 1.0
 * @description
 * @create 2025/4/22 17:14
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 在controller之前执行
     * 登录凭证校验
     * 1：获取请求中的jwt
     *    获取不到直接拦截
     * 2：用系统jwt密钥去解密
     *    解不开直接拦截
     * 3：判断redis对应jwt是否过期
     *    如果过期了还是要拦截
     *
     * 4： 给该jwt时间续期
     *
     * 5: 放行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        //1：获取请求中的jwt（从请求头中获取jwt）
        String jwt = request.getHeader("authorization");

        String jsonStr = JSON.toJSONString(ResponseData.fail(ResponseEnum.NO_LOGIN));
        response.setContentType("application/json;charset=UTF-8");
        if (jwt == null){
            response.getWriter().print( jsonStr);
            return false;
        }
        //2：用系统jwt密钥去解密
        if (!JWTUtil.decode(jwt)){
            //拦截
            response.getWriter().print( jsonStr);
            return false;
        }
        //3：判断redis对应jwt是否过期,根据key到reids查询
        Map userInfo = JWTUtil.getJWTUserInfo(jwt);
        Object userId = userInfo.get("id");

        String redisJWT = stringRedisTemplate.opsForValue().get("JWT:"+userId);
        if (!jwt.equals(redisJWT)){
            response.getWriter().print( jsonStr);
            return false;
        }
        //4： 给该jwt时间续期
        stringRedisTemplate.expire("JWT:"+userId,20, TimeUnit.DAYS); //给指定key加时间
        return true;
    }
}
